package utils

import (
	"arc_srv4/common"
	"arc_srv4/logutils"
	"encoding/json"
	"go.uber.org/zap"
	"gopkg.in/gomail.v2"
	"strconv"
	"strings"
)

func SendMail(mailConn map[string]string, mailTo []string, subject, body string) error {
	port, _ := strconv.Atoi(mailConn["port"]) //转换端口类型为int
	m := gomail.NewMessage()
	alias := mailConn["alias"]
	if alias != "" {
		m.SetHeader("From", m.FormatAddress(mailConn["user"], alias)) //添加别名，即“XX官方”
	} else {
		m.SetHeader("From", mailConn["user"])
	}
	m.SetHeader("To", mailTo...)    //发送给多个用户
	m.SetHeader("Subject", subject) //设置邮件主题
	m.SetBody("text/html", body)    //设置邮件正文

	d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["password"])
	err := d.DialAndSend(m)
	return err
}

func SendEmailSys(body string) {
	body = "【邮件通知】 " + body
	mailFromS, mailTo, subject := ConvertJsonToMap(common.MailCfg.From), common.MailCfg.To, common.MailCfg.Subject
	for _, v := range mailFromS {
		strF, _ := json.Marshal(v)
		strT := strings.Join(mailTo, ",")

		for i := 0; i < common.MailCfg.RetryTime; i++ {
			err := SendMail(v, mailTo, subject, body)
			if err != nil {
				logutils.Logger.Warn("发送邮件失败", zap.String("发件人",
					string(strF)), zap.String("收件人", strT),
					zap.String("主题", subject),
					zap.String("内容", body),
					zap.String("错误", err.Error()),
					zap.Bool("成功", false),
				)
				i++
				continue
			} else {
				break
			}

		}
		logutils.Logger.Info("发送邮件成功", zap.String("收件人",
			string(strF)), zap.String("收件人", strT),
			zap.String("主题", subject),
			zap.String("内容", body),
			zap.Bool("成功", true),
		)
	}
}
